package com.study;

import java.util.Arrays;
import java.util.Iterator;
import java.util.function.Consumer;
import java.util.stream.IntStream;

public class DynamicArray implements Iterable<Integer>
{
    private int size;           // 逻辑大小
    private int capacity = 8;   // 容量 数组的长度
    private int[] array = {};   // 保存元素的数组

    public void addLast(int value)
    {
        add(size, value);
    }

    public void add(int index, int value)
    {
        checkAndGrow();

        if (index < 0 || index > size) return;
        if (index < size) {
            // 如果加在中间，需要把后面的元素向后移一下
            System.arraycopy(array, index,
                    array, index + 1, size - index);
        }
        array[size++] = value;
    }

    private void checkAndGrow()
    {
        if (size == 0) {
            array = new int[capacity];
        } else if (size == capacity) {
            capacity += capacity >> 1;
            int[] newArray = new int[capacity];
            System.arraycopy(array, 0, newArray, 0, size);
            array = newArray;
        }
    }

    public int remove(int index)
    {
        int removed = array[index];
        if (index < size - 1) {
            // index 不是最后一个元素，则需要把 index 后面所有的元素都向前移动一下
            System.arraycopy(array, index + 1,
                    array, index, size - index - 1);
        }
        size--;
        return removed;
    }

    // 遍历
    public void foreach(Consumer<Integer> consumer)
    {
        for (int i = 0; i < size; i++) {
            consumer.accept(array[i]);
        }
    }

    @Override
    public Iterator<Integer> iterator()
    {
        return new Iterator<>()
        {
            int i = 0;

            @Override
            public boolean hasNext()
            {
                return i < size;
            }

            @Override
            public Integer next()
            {
                return array[i++];
            }
        };
    }

    public IntStream stream()
    {
        return IntStream.of(Arrays.copyOfRange(array, 0, size));
    }
}
